package vip.xiaonuo.common.util;

import org.apache.commons.lang3.StringUtils;

/**
 * @author zjt
 * @description
 * @date 2024/12/4 09:34
 */
public class CommonStringFormatUtil {


    // 用于计算校验码的权重因子
    private static final int[] WEIGHT_FACTORS = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};

    // 用于计算校验码的校验码表
    private static final char[] CHECK_CODES = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};

    public static boolean isValidCardId(String cardId) {
        if (StringUtils.isEmpty(cardId) || cardId.length() != 18) {
            return false;
        }
        // 检查是否全为数字或最后一位为X
        for (int i = 0; i < 17; i++) {
            if (!Character.isDigit(cardId.charAt(i))) {
                return false;
            }
        }
        char lastChar = cardId.charAt(17);
        if (!Character.isDigit(lastChar) && lastChar != 'X' && lastChar != 'x') {
            return false;
        }
        // 计算校验码并验证
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            int digit = Character.getNumericValue(cardId.charAt(i));
            sum += digit * WEIGHT_FACTORS[i];
        }
        int mod = sum % 11;
        char expectedCheckCode = CHECK_CODES[mod];
        return (lastChar == expectedCheckCode) || (Character.toLowerCase(lastChar) == Character.toLowerCase(expectedCheckCode));
    }

    public static boolean isValidPhone(String str) {
        // 使用正则表达式进行匹配
        String regex = "^1\\d{10}$";
        return str.matches(regex);
    }
}
